package com.tingyuge.io.sqlSession;

import com.tingyuge.io.pojo.Configuration;
import com.tingyuge.io.pojo.MappedStatement;
import com.tingyuge.utils.GenericTokenParser;
import com.tingyuge.utils.ParameterMapping;
import com.tingyuge.utils.ParameterMappingTokenHandler;

import javax.sql.DataSource;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.sql.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author xiaodao
 * @version 1.0
 * @date 2021/6/6
 */
public class SimpleExecutor implements Executor {

    //object... user
    public <E> List<E> query(Configuration configuration, MappedStatement mappedStatement, Object... params) throws Exception {
        // 1. 获取连接

        DataSource dataSource = configuration.getDataSource();
        Connection connection = dataSource.getConnection();
        //2. 获取sql语句   select * from user where id =#{id} and username =#{username}
        //  转换sql语句  select *from user where id = ? and username = ?  转换过程中,需要对#{} 解析进行储存
        String sql = mappedStatement.getSql();
        BoundSql boundSql = getBoundSql(sql);
        //3 .获取预处理对象: prepareStatement

        PreparedStatement preparedStatement = connection.prepareStatement(boundSql.getSqlText());

        //4. 设置参数
        //获取参数的全路径
        String parameterType = mappedStatement.getParameterType();
        Class<?> parameterClass = getClassType(parameterType);
        List<ParameterMapping> parameterMappingList = boundSql.getParameterMappingList();
        List<Object> paramList = new ArrayList<Object>();
        for (int i = 0; i < parameterMappingList.size(); i++) {
            ParameterMapping parameterMapping = parameterMappingList.get(i);
            String content = parameterMapping.getContent();
            //反射
            Field declaredField = parameterClass.getDeclaredField(content);
            declaredField.setAccessible(true);
            Object o = declaredField.get(params[0]);
            paramList.add(o);
            preparedStatement.setObject(i+1,o);
        }
        //5.执行SQL
     /*   System.out.println("执行SQL : " + boundSql.getSqlText()+paramList.stream().forEach(System.out::print));
        System.out.println("执行参数: "+paramList.toArray());*/
        ResultSet resultSet = preparedStatement.executeQuery();
        Class<?> classType = getClassType(mappedStatement.getResultType());

        List<Object> objects = new ArrayList<Object>();
        //6.封装返回值
        while (resultSet.next()){
            Object o = classType.newInstance();
            ResultSetMetaData metaData = resultSet.getMetaData();
            for (int i = 1; i <= metaData.getColumnCount(); i++) {
                //字段名
                String columnName = metaData.getColumnName(i);
                //字段值
                Object value = resultSet.getObject(columnName);

                //使用反射或者内省,根据数据库表和实体的对应关系,完成封装

                PropertyDescriptor propertyDescriptor = new PropertyDescriptor(columnName,classType);

                Method writeMethod = propertyDescriptor.getWriteMethod();
                writeMethod.invoke(o, value);
            }
            objects.add(o);
        }
        return (List<E>) objects;
    }

    private Class<?> getClassType(String parameterType) throws ClassNotFoundException {

        if(null !=parameterType){
            Class<?> aClass = Class.forName(parameterType);
            return aClass;
        }
        return null;
    }

    /**
     * 1.将#{} 的解析工作 1.将#{}使用 ? 进行代替
     * 2.将#{}里的值,进行存储
     *
     * @param sql
     * @return
     */
    private BoundSql getBoundSql(String sql) {
        //标记处理类: 配置标记解析器来完成对占位符的解析处理工作
        ParameterMappingTokenHandler parameterMappingTokenHandler = new ParameterMappingTokenHandler();
        GenericTokenParser genericTokenParser = new GenericTokenParser("#{", "}", parameterMappingTokenHandler);
        //解析出来的SQL
        String parse = genericTokenParser.parse(sql);
        //解析出来的值
        List<ParameterMapping> parameterMappings = parameterMappingTokenHandler.getParameterMappings();
        BoundSql boundSql = new BoundSql(parse, parameterMappings);
        return boundSql;
    }
}
